/* eslint-disable no-console*/

import db from './datastore'

var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
 
// 创建服务器
let webserver = http.createServer( function (request, response) {
  
   // 解析请求，包括文件名
   var pathname = url.parse(request.url).pathname;
   
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
   if(pathname.startsWith('/file')){
     let id = pathname.substr('/file/'.length);
     let fileInfo = db.read().get('file_share')
       .find({ id: id })
       .value();
     if(!fileInfo){
       response.writeHead(404, {'Content-Type': 'text/html'});
       response.end();
       return;
     }
     console.log('filePath:' + fileInfo.filePath);
     let stats = fs.statSync(fileInfo.filePath);
     response.setHeader('Content-Type', 'application/octet-stream');
     // filename必须使用urlencode()进行编码
     // 否则有可能报错：TypeError: The header content contains invaild charaters
     let urlencode = require('urlencode');
     response.setHeader('Content-Disposition', 'attachment; filename=' + urlencode(fileInfo.fileName));
     response.setHeader('Content-Length', stats.size);
     fs.createReadStream(fileInfo.filePath).pipe(response);
   }else if(pathname.startsWith('/text')){
     let id = pathname.substr('/text/'.length);
     let textInfo = db.read().get('text_share')
       .find({ id: id })
       .value();
     if(!textInfo){
       response.writeHead(404, {'Content-Type': 'text/html'});
       response.end();
       return;
     }
     
     // 测试环境和打包发布之后的textshare.ejs所处的位置不一样
     // 所以这里要做区别处理
     let templateFilePath = path.join(__dirname, '../../static/textshare.ejs');
     if (process.env.NODE_ENV === 'production'){
       templateFilePath = path.join(__dirname, 'static' , 'textshare.ejs');
     }
     
     fs.readFile(templateFilePath, 'utf-8', (err, data) => {
       if (err) {
         response.writeHead(500, {'Content-Type': 'text/html'});
         response.write(err.toString(), 'utf-8');
         response.end();
         return;
       }
       console.log('before reder:\n' + data);
       let ejs = require('ejs');
       let html = ejs.render(data, {title: textInfo.title, content: textInfo.content});
       console.log('after reder:\n' + html);
       response.writeHead(200, {'Content-Type': 'text/html'});
       response.write(html, 'utf8');
       response.end();
     });
   }
});

export default webserver;
const PORT = 8008;
export {PORT}